package summary;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:13
 * https://leetcode-cn.com/problems/pseudo-palindromic-paths-in-a-binary-tree/
 */
public class Title1457 {

    static class TreeNode {
        int val;

        TreeNode left;

        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static int pseudoPalindromicPaths (TreeNode root) {
        if (root == null) {
            return 0;
        }
        //<root.val, 次数>
        Map<Integer, Integer> hash = new HashMap<>();
        return dfs(root, hash);
    }

    private static int dfs(TreeNode root, Map<Integer, Integer> hash) {
        if (root == null) {
            return 0;
        }
        int count = 0;
        hash.put(root.val, hash.getOrDefault(root.val, 0) + 1);
        if (root.left == null & root.right == null) {
            int times = 0;
            for (Integer temp : hash.values()) {
                if (temp % 2 != 0) {
                    times++;
                }
            }
            if (times <= 1) {
                count++;
            }
        }
        count += dfs(root.left, hash);
        count += dfs(root.right, hash);
        hash.put(root.val, hash.getOrDefault(root.val, 0) - 1);
        return count;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(1);
        root.right = new TreeNode(1);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.left.right.right = new TreeNode(1);
        pseudoPalindromicPaths(root);
    }
}
